import { container } from "tsyringe"
import { Context } from "./ctx"
import { CURRENT_TASK, TASKS } from "./task"
import { Task } from "../autox/task"
import { APPS, CURRENT_APP } from "./app"
import { $, updateFloat } from "../utils"

export class Robot {
    start(type: `RandomFindRedPacketTask` | `FollowFindRedPacketTask` | `TakeRedPacketTask` = `RandomFindRedPacketTask`) {
        const ctx = container.resolve(Context)
        ctx.set(`CURRENT_TASK_TYPE`, type)
        const tasks = container.resolveAll(TASKS)
        const currentTask = tasks.find(it => it.type === type)
        if (!currentTask) {
            log(`无匹配任务`)
            return;
        }
        ctx.set(CURRENT_TASK, currentTask);
        updateFloat({ currentTask: currentTask.title })
        log(`正在执行[${currentTask.title}]任务`)
        const task = container.resolve(Task)
        task.start(() => {
            const apps = container.resolveAll(APPS)
            log(`总共有${apps.length}个APP`)
            while (true) {
                const currentPackageName = $.getCurrentPackageName()
                const app = apps.find(app => app.packageName === currentPackageName)
                if (!app) {
                    log(`current package name is ${currentPackageName}`)
                }
                const currentApp = ctx.get(CURRENT_APP)
                if (app !== currentApp) {
                    currentApp?.close();
                    ctx.set(CURRENT_APP, app)
                    app?.open();
                    updateFloat({ currentApp: app?.title })
                }
                sleep(1000 * 5)
            }
        })
    }
}